#include <cstring>
#include <iostream>
#include <unistd.h>

#include "../logs/bin.hpp"

/*扩展一个以时间作为入职文件滚动切换类型的日志落地模块
    1.以当前时间，取模时间段大小，可以得到当前时间段是第几个时间段
    2.每次以当前系统时间取模，判断与当前文件的时间段是否一致，不一致则代表不是同一个时间段
*/
enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};
class RollByTimeSink : public bin::LogSink
{
public:
    RollByTimeSink(const std::string &basename, TimeGap gap_type)
        : _basename(basename), _name_count(0)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = _gap_size == 1 ? bin::util::Date::now() : bin::util::Date::now() % _gap_size; // 获取当前时间段
        std::string pathname = createNewFile();
        // 创建文件目录
        bin::util::File::createDirectory(bin::util::File::path(pathname));
        // 创建并打开日志文件
        _ofs.open(pathname, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    // 在写入前判断时间段，不符合要切换文件
    void log(const char *data, size_t len)
    {
        time_t cur = _gap_size == 1 ? bin::util::Date::now() : bin::util::Date::now() % _gap_size; // 获取当前时间段
        if (cur != _cur_gap)
        {
            _ofs.close(); // 关闭原来已经打开的文件
            std::string pathname = createNewFile();
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_gap = cur;
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile() // 生成文件名
    {
        // 获取系统时间，以时间构建文件名扩展名
        time_t t = bin::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
        filename << "-";
        filename << _name_count++;
        return filename.str();
    }

private:
    size_t _name_count; // 名称计数器，防止同一时间生成了多个文件，这些文件名字都相同
    // 基础文件名 + 扩展文件名 生成最终文件名
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 记录当前是第几个时间段
    size_t _gap_size; // 记录时间段大小
};


int main()
{

    std::unique_ptr<bin::LoggerBuilder> builder(new bin::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(bin::LogLevel::value::WARN);
    builder->buildFormatter("[%c][%f:%l]%m%n");
    builder->buildLoggerType(bin::LoggerType::LOGGER_ASYNC);
    // builder->buildEnableUnSafeAsync();
    builder->buildSink<bin::StdoutSink>();
    builder->buildSink<bin::FileSink>("./logfile/test.log");
    builder->buildSink<RollByTimeSink>("./logfile/rool-", TimeGap::GAP_SECOND);
    bin::Logger::ptr logger = builder->build();

    logger->info("测试开始");

    logger->debug("日志测试");
    logger->info("日志测试");
    logger->warn("日志测试");
    logger->error("日志测试");
    logger->fatal("日志测试");

    time_t cur = bin::util::Date::now();
    while(bin::util::Date::now() < cur + 5)
    {
        logger->fatal("日志测试");
        usleep(1000);
    }

    logger->info("测试结束");

    return 0;
}